var layer, form, upload, laytpl, util;
$(function () {
    layui.use(['form', 'layer', 'upload', 'laytpl', 'util'], function () {
        layer = layui.layer;
        form = layui.form;
        upload = layui.upload;
        laytpl = layui.laytpl;
        util = layui.util;


        upload.render({
            elem: '#photo-btn',
            url: '/ajax/upload/upload_images',
            before: function (obj) {
                layer.load(2);
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                    var type = $("#user_photo").val();
                    if (type == 1) {
                        $('#photo-btn').attr('src', result);
                    } else {
                        $('#demo1').attr('src', result).show(); //图片链接（base64）
                    }
                });
            },
            done: function (res) {
                layer.closeAll();
                //如果上传失败
                if (res.code == 0) {

                    var type = $("#user_photo").val();
                    if (type == 1) {
                        $.ajax({
                            type: 'POST',
                            url: $("#save").val(),
                            data: {photo: res.result},
                            dataType: "json",
                            success: function (data) {
                                layer.msg(data.msg);
                            }
                        });
                    } else {
                        layer.msg('上传成功');
                        $("#images").val(res.data.src);
                    }
                } else {
                    return layer.msg('上传失败');
                }

            },
            error: function () {
                //演示失败状态，并实现重传
                // var demoText = $('#demoText');
                // demoText.html(
                //     '<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'
                // );
                // demoText.find('.demo-reload').on('click', function () {
                //     uploadInst.upload();
                // });
            }
        });

        upload.render({
            elem: '#photo-btn2',
            url: '/ajax/upload/upload_images',
            before: function (obj) {
                layer.load(2);
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo2').attr('src', result); //图片链接（base64）
                });
            },
            done: function (res) {
                layer.closeAll();
                //如果上传失败
                if (res.code == 0) {

                    layer.msg('上传成功');
                    $("#images2").val(res.data.src);
                } else {
                    return layer.msg('上传失败');
                }

            },
            error: function () {
                //演示失败状态，并实现重传
                // var demoText = $('#demoText');
                // demoText.html(
                //     '<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'
                // );
                // demoText.find('.demo-reload').on('click', function () {
                //     uploadInst.upload();
                // });
            }
        });

        upload.render({
            elem: '.uploadImages',
            url: '/ajax/Upload/upload_images',
            multiple: true,
            before: function (obj) {
                layer.load();
                var i = this.item.index('.uploadImages');
                obj.preview(function (index, file, result) {
                    $('.showImages:eq(' + i + ')').append('' +
                        '<div class="upload-photo-box">' +
                        '<div class="loaded-photo-thumbnail">' +
                        '<img src="' + result + '" style="width: 35%"><a href="javascript:;" class="uploadDels">删除</a>' +
                        '</div>' +
                        '</div>')
                });
            },
            done: function (data) {
                layer.closeAll();
                if (data.code == 0) {
                    var i = this.item.index('.uploadImages');
                    var inpName = this.item.attr('inpName');
                    $('.showImages:eq(' + i + ')').append('<input type="hidden" name="images[]" value="' + data.data.src + '" class="uploadInps"/>');
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }
            },
            error: function () {
                layer.closeAll('loading');
            }
        });

        $('body').on('click', '.uploadDels', function () {
            var i = $(this).index('.uploadDels');
            $('.upload-photo-box:eq(' + i + ')').remove();
            $('.uploadInps:eq(' + i + ')').remove();
        })


        var os = true;
        form.on('submit(save)', function (data) {
            if (os !== true) return false;
            os = false;
            layer.load();
            var btn = $(this);
            btn.attr('disabled', true);
            formObj = $($(this).attr('formObj'));
            url = formObj.attr('action');
            $.ajax({
                type: 'POST',
                url: url,
                data: formObj.serialize(),
                dataType: "json",
                success: function (data) {
                    layer.closeAll();
                    if (data.code == 1) {
                        layer.msg(data.msg, {time: 1500}, function () {
                            if (data.url) {
                                location.href = data.url;
                            } else {
                                window.location.reload();
                            }

                        });
                    } else if (data.code == 3) {
                        layer.msg(data.msg, {time: 1500}, function () {
                            location.href = document.referrer;
                        });
                    } else {
                        os = true;
                        layer.msg(data.msg);
                        btn.removeAttr('disabled');
                    }
                },
                error(e) {
                    layer.closeAll();
                    btn.removeAttr('disabled');
                }
            });
            return false;
        })

        form.on('select(prov)', function(data){
            get_area(2, data.value, '#city');
            $("#county").html('<option value="">区/县</option>');
            $("#town").html('<option value="">街道/乡镇</option>');

        });
        form.on('select(city)', function(data){
            $("#town").html('<option value="">街道/乡镇</option>');
            get_area(3, data.value, '#county');
        });

        form.on('select(county)', function(data){
            get_area(4, data.value, '#town');
        });

        form.on('select(type)', function(data){
           switch (data.value) {
               case '1':
                   $('.prov').show();
                   $('.city').show();
                   $('.county').show();
                   $('.town').show();
                   break;
               case "2":
                   $('.prov').show();
                   $('.city').show();
                   $('.county').show();
                   $('.town').hide();
                   break;
               default:
                   $('.prov').hide();
                   $('.city').hide();
                   $('.county').hide();
                   $('.town').hide();
           }
        });


        function get_area(depth, parent_id, name) {
            $.ajax({
                type: 'GET',
                url: '/index/index/getAreas',
                data: {depth: depth, parent_id: parent_id},
                dataType: "json",
                success: function (data) {
                    if (data.code == 1) {
                        if (data.result.length > 0) {
                            let tpl = document.getElementById('template').innerHTML;
                            laytpl(tpl).render(data, function (html) {
                                $(name).html(html);
                            });
                            form.render();
                        }
                    } else {
                        layer.msg('加载失败');
                    }
                }
            });
        }
    });
    $('.show_img').click(function(){
        var img = $(this).attr('data-src');
        layer.open({
            title: '收款码',
            shade: 0.6,
            content: '<img src="'+img+'" style="width:100%;" />'
        });
    });
});

function layer_open(title, content) {
    $('.textAlert').show();
    layer.open({
        type: 1,
        shade: [0.8, '#021D33'],
        shadeClose: false,
        closeBtn: 0,
        area: ['300px', 'auto'], //宽高
        title: title,
        content: '<div class="textAlert"><div class="textAlert-count">' + content + '</div><a class="closeTextAlert" href="javascript:close_open();">确定</a></div>',
    });
}

function close_open(type) {
    $('.textAlert').hide();
    layer.closeAll();
    if (type) window.location.reload();
}

var os = true;

function _ajax(url, data, type) {
    if (os !== true) return false;
    os = false;
    layer.load(2);
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        dataType: "json",
        success: function (data) {
            layer.closeAll();
            if (data.code == 1) {
                layer.msg(data.msg, {time: 1500}, function () {
                    if (data.url) {
                        location.href = data.url;
                    } else {
                        location.reload();
                    }
                });
            } else if (data.code == 3) {
                layer.msg(data.msg, {time: 1500}, function () {
                   location.href = document.referrer;
                });
            } else {
                os = true;
                layer.msg(data.msg);
            }
        }
    });
}

$(".load_more").click(function () {
    if ($('.load_more').text() !== '没有更多了') {
        layer.load(2);
        let page = $(this).attr('data-page');
        let type = $(this).attr('data-type');
        let url = $(this).attr('data-url');
        get_list(parseInt(page) + 1, type, url)
        layer.closeAll();
    }
});

function get_list(page, type, url, down) {
    $.ajax({
        type: 'GET',
        url: url,
        data: {page: page, type: type},
        dataType: "json",
        success: function (data) {
            if (data.code == 1) {
                if (data.result.length > 0) {
                    var tpl = document.getElementById('template').innerHTML;
                    laytpl(tpl).render({data: data.result, page: data.page, type: type}, function (html) {
                        if (data.page > 1) {
                            $('.tpl_list').append(html);
                        } else {
                            $('.tpl_list').html(html);
                        }
                        $('.load_more').attr('data-page', data.page);
                        if (data.result.length < 20) {
                            $('.load_more').hide();
                        }
                    });
                    if (down) {
                        count_down();
                    }
                } else {
                    $('.load_more').text('没有更多了');
                }

            } else {
                layer.msg('加载失败');
            }
        }
    });
}

function count_down() {
    $(".count_down").each(function () {
        var that = $(this);
        var count_down = that.attr('data-end');
        var start = new Date("{:date('Y')}", "{:date('m')}", "{:date('d')}", "{:date('H')}", "{:date('i')}", "{:date('s')}");
        count_down = count_down.split(",");
        var end = new Date(count_down[0], count_down[1], count_down[2], count_down[3], count_down[4], count_down[5]);
        util.countdown(end, start, function (date, serverTime, timer) {
            if (date[0] === 0 && date[1] === 0 && date[2] === 0 && date[3] === 0) {
                that.text('加载中');
            } else {
                var str = date[1] + ' 时 ' + date[2] + ' 分 ' + date[3] + ' 秒';
                if(date[1] === 0 && date[2] === 0 && date[3] === 0){
                    location.reload();
                }else{
                    that.text(str);
                }
            }
        });
    });
}

function load_href(url,type = 1) {
    layer.load(2);
    if(type == 1){
        location.href = document.referrer;
    }else{
        location.href = url;
    }


}



